from sqlalchemy import JSON, Column, Integer, String, Text, DateTime, SmallInteger, Enum
from sqlalchemy.ext.declarative import declarative_base
from .base import Base
from datetime import datetime
from sqlalchemy import event  
import json
from pydantic import BaseModel, Field
from typing import Optional
class Thumbnail(BaseModel):
    """
    缩略图信息存储于 news 表的 thumbnail JSON 字段中, 此类用于序列化
    """
    url: Optional[str] = Field(description="缩略图链接")
    data: str = Field(default='', description="base64编码的图片数据")
    content_type: Optional[str] = Field(description="缩略图类型")


class News(Base):
    """
    创建新闻记录，其中包含缩略图信息
    news_item = News(
        title="突发新闻标题",
        content="这里是新闻的内容。",
        ... 其他字段 ...
        thumbnail={"data": "iVBORw0KGgoAAAANSUhEUgAAAAUA...", "contentType": "image/jpeg"}
    )
        fin_tags=["中国","上市公司","基金"]
        stock_list=["000001.XSHE","000002.XSHE"]
    """
    __tablename__ = 'news'

    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(255), nullable=False)  # 新闻标题
    content = Column(Text, nullable=False)  # 新闻内容
    source = Column(String(255), nullable=False)  # 来源
    published_date = Column(DateTime, nullable=False)  # 发布日期
    url = Column(String(255), unique=True, nullable=False)  # 新闻的原始链接
    category = Column(Enum('quick', 'regular', name='category'), nullable=False)  # 新闻类别，快讯或常规新闻
    thumbnail = Column(JSON, nullable=True)  # 缩略图，存储二进制数据
    author = Column(String(255), nullable=True)  # 作者
    fin_tags = Column(JSON, nullable=True)
    stock_list = Column(JSON, nullable=True)
    listed_company = Column(SmallInteger, nullable=True, default=0)
    created_time = Column(DateTime, default=datetime.now)  # 记录创建时间  
    updated_time = Column(DateTime, default=datetime.now, onupdate=datetime.now)  # 记录最后更新时间

    def check_if_update_needed(self, new_item):
        # 比较基本字段  
        if (self.title != new_item.title or  
            self.content != new_item.content or  
            self.source != new_item.source or  
            self.published_date != new_item.published_date or  
            self.url != new_item.url or  
            self.category != new_item.category or  
            self.author != new_item.author or  
            self.listed_company != new_item.listed_company):  
            return True  
          
        # 比较 JSON 字段  
        self_fin_tags = set(json.loads(self.fin_tags) if self.fin_tags else [])  
        new_fin_tags = set(json.loads(new_item.fin_tags) if new_item.fin_tags else [])  
        if self_fin_tags != new_fin_tags:  
            return True  
          
        self_stock_list = set(json.loads(self.stock_list) if self.stock_list else [])  
        new_stock_list = set(json.loads(new_item.stock_list) if new_item.stock_list else [])  
        if self_stock_list != new_stock_list:  
            return True  
  
        # 如果需要，也可以比较其他可能的 JSON 字段，比如 thumbnail  
        # 注意：thumbnail 可能是一个复杂的 JSON 结构，需要更复杂的比较逻辑  
  
        # 如果没有任何不同，则返回 False  
        return False
    def __repr__(self):
        return f"<News(id={self.id}, title='{self.title}', source='{self.source}', published_date='{self.published_date}', news_category='{self.category}')>"
    
# 监听before_insert事件，在插入新闻记录前设置created_time和updated_time  
@event.listens_for(News, 'before_insert')  
def set_timestamps(mapper, connection, target):  
    target.created_time = datetime.now()  
    target.updated_time = datetime.now()  

# 监听before_update事件，在更新新闻记录前更新updated_time  
@event.listens_for(News, 'before_update')  
def update_timestamp(mapper, connection, target):  
    target.updated_time = datetime.now()